package day08.handler;

import day08.packet.LoginRequestPacket;
import day08.packet.LoginResponsePacket;
import day08.packet.MessageResponsePacket;
import day08.packet.Packet;
import day08.util.LoginUtil;
import day08.util.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * @author chenshijie
 * @date 2023/12/21 12:14
 */

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录");

        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(123);
        loginRequestPacket.setUsername("yu");
        loginRequestPacket.setPassword("password");

        // 编码
        ByteBuf buffer = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginRequestPacket);

        // 写数据
        ctx.channel().writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodeC.INSTANCE.decode(byteBuf);

        if (packet instanceof LoginResponsePacket) {

            loginResponse(ctx, (LoginResponsePacket) packet);

        } else if (packet instanceof MessageResponsePacket) {

            messageResponse(ctx, (MessageResponsePacket) packet);

        } else {
            System.out.println("无法解析数据类型");
        }
    }

    private static void loginResponse(ChannelHandlerContext ctx, LoginResponsePacket loginResponsePacket) {

        if (loginResponsePacket.isSuccess()) {
            System.out.println(new Date() + "客户端登录成功");
            System.out.println("是否已经登陆" + LoginUtil.hasLogin(ctx.channel()));
            LoginUtil.markAsLogin(ctx.channel());
            System.out.println("是否已经登陆" + LoginUtil.hasLogin(ctx.channel()));
        } else {
            System.out.println(new Date() + "客户端登录失败：" + loginResponsePacket.getMsg());
        }
    }

    private static void messageResponse(ChannelHandlerContext ctx, MessageResponsePacket messageResponsePacket) {

        if (LoginUtil.hasLogin(ctx.channel())) {
//            log.println(new Date() + ": 收到了服务端的消息: " + messageResponsePacket.getMessage());
            System.out.println(new Date() + ": 收到了服务端的消息: " + messageResponsePacket.getMessage());
        }
    }
}
